package com.renwei.yunlong.activity.me;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.ImageUploadBean;
import com.renwei.yunlong.event.MinePageRefreshEvent;
import com.renwei.yunlong.global.EventKey;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.UploadManger;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;
import io.github.xudaojie.qrcodelib.zxing.DensityUtils;

/**
 * Project :  yunaandroid.
 * Package name: com.renwei.yunlong.activity
 * Created by :  Benjamin.
 * Created time: 2017/10/24 11:02
 * Changed by :  Benjamin.
 * Changed time: 2017/10/24 11:02
 * Class description:
 */

public class UserAddCertificateActivity extends BaseActivity implements View.OnClickListener, InvokeListener, TakePhoto.TakeResultListener, HttpTaskListener {
    private static final String TAG = "UserAddCertificateActivity";
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.certificate_name)
    TextView certificateName;
    @Bind(R.id.certificate_level)
    TextView certificateLevel;
    @Bind(R.id.iv_certificate_image)
    ImageView ivCertificateImage;
    @Bind(R.id.btn_certificate_comit)
    Button btnCertificateComit;
    @Bind(R.id.rl_certificate_name)
    RelativeLayout rlCertificateName;
    @Bind(R.id.rl_certificate_level)
    RelativeLayout rlCertificateLevel;
    @Bind(R.id.ll_certificate_image)
    LinearLayout llCertificateImage;
    private ArrayList<ImageUploadBean> listImageResult;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    ImageUploadBean image;

    private PromptDialog promptDialog;
    private Uri temmImageUrl;
    private File newFile = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_add_certificate);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        getTakePhoto().onCreate(savedInstanceState);
        promptDialog = new PromptDialog(this);
        listImageResult = new ArrayList<>();
        initView();
    }

    private void initView() {
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        tvTitle.setText("证书");
        tvRight.setVisibility(View.GONE);
        btnCertificateComit.setOnClickListener(this);
        rlCertificateName.setOnClickListener(this);
        rlCertificateLevel.setOnClickListener(this);
        llCertificateImage.setOnClickListener(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        getTakePhoto().onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                this.finish();
                break;
            case R.id.btn_certificate_comit:
                checkParamsAndComit();
                break;
            case R.id.ll_certificate_image:
                PromptButton cancle = new PromptButton("取消", null);
                File file = new File(getApplication().getCacheDir(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                temmImageUrl = Uri.fromFile(file);
                LogUtil.e("onClick: ", temmImageUrl.toString());
                //默认两个按钮为Alert对话框，大于三个按钮的为底部SHeet形式展现
                promptDialog.showAlertSheet("", true, cancle,
                        new PromptButton("打开相册", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickFromGallery();
                            }
                        }), new PromptButton("拍照", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickFromCapture(temmImageUrl);
                            }
                        }));
                break;
            case R.id.rl_certificate_name:
                Intent nameIntent = new Intent(this, UserCertificateNameActivity.class);
                nameIntent.putExtra("name", certificateName.getText().toString());
                nameIntent.setAction("1");
                startActivityForResult(nameIntent, 1);
                break;
            case R.id.rl_certificate_level:
                Intent levelIntent = new Intent(this, UserCertificateNameActivity.class);
                levelIntent.putExtra("level", certificateLevel.getText().toString());
                levelIntent.setAction("2");
                startActivityForResult(levelIntent, 2);
                break;
            default:
                break;

        }
    }


    public String getLevel() {
        String leve = String.valueOf(certificateLevel.getText().toString());
        switch (leve) {

            case ("五级"):
                leve = "5";
                break;
            case ("四级"):
                leve = "4";
                break;
            case ("三级"):
                leve = "3";
                break;
            case ("二级"):
                leve = "2";
                break;
            case ("一级"):
                leve = "1";
                break;
            default:
                leve = "0";
                break;
        }
        return leve;

    }

    public void checkParamsAndComit() {
        String name = String.valueOf(certificateName.getText().toString());
        String leve = String.valueOf(getLevel());
        if (name.length() == 0 || leve.length() == 0) {
            showCenterInfoMsg("提交信息不全");
            return;
        } else if (image == null || image.getPath().length() == 0) {
            showCenterInfoMsg("请先选择证件照");
            return;
        } else {
            HashMap map = new HashMap();
            ServiceRequestManager manager = ServiceRequestManager.getManager();
            if ("1".equals(companyType)) {//业主
                map.put("correlationId", String.valueOf(ownerBean.getRows().getEmployeeId()));
                map.put("qualName", String.valueOf(name));//资质名称
            } else {//服务商
                map.put("correlationId", String.valueOf(serviceLoginBean.getRows().getEmployeeId()));
                map.put("qualName", String.valueOf(name));//资质名称
            }
            map.put("qualGrade", String.valueOf(leve));//资质等级,(必填)（一级：1、二级:2、三级:3、四级:4、五级:5）
            map.put("attachName", image.getName());//证书图片名称
            map.put("attachPath", image.getPath());//证书图片路径，
            map.put("attachSize", image.getSize());
            map.put("type", "4");
          /*  map.put("id", String.valueOf(System.currentTimeMillis()));*/
            manager.UserCommitCertificate(this, JsonMapUtil.mapToJson(map), this);
        }

    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(UserAddCertificateActivity.this, this));
        }
        configCompress(takePhoto);
        return takePhoto;
    }

    //配置图像压缩相关
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxSize(1024000)
                .create();
        config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, false);
    }

    /**
     * 配置图片裁剪相关参数
     *
     * @return 压缩详情
     */
    private CropOptions getCropOptions() {
        int height = 800;
        int width = 800;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case 1:
                    certificateName.setText(data.getStringExtra("name"));
                    break;
                case 2:
                    certificateLevel.setText(data.getStringExtra("level"));
                    break;
                    default:
                    break;

            }
        }
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void takeSuccess(TResult result) {
        //牌照成功之后上传图片图片上传成功后 回掉onSuccess
        try {
            newFile = new File(result.getImage().getCompressPath());
            if (newFile.exists()) {
                //上传文件到中间平台
                UploadManger manger = UploadManger.getManager();
                String versionCode = "";
                String companyCode = "";
                if ("1".equals(companyType)) {
                    versionCode = ownerBean.getRows().getCompany().getVersionCode();
                    companyCode = ownerBean.getRows().getCompany().getCompanyCode();
                } else {
                    versionCode = serviceLoginBean.getRows().getCompany().getVersionCode();
                    companyCode = serviceLoginBean.getRows().getCompany().getCompanyCode();
                }
                manger.uploadUserCertificate(UserAddCertificateActivity.this, newFile, this, versionCode, companyCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e(e.getMessage());
            showCenterInfoMsg(this.getString(R.string.tip_file_is_not_exist));
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        LogUtil.e(TAG + "takeFail：" + result);

    }

    @Override
    public void takeCancel() {
        LogUtil.e(TAG + "takeCancel：");

    }

    @Override
    public void onSuccess(int requestId, String result) {
        LogUtil.e("成功requestId :" + requestId + "result:" + result);
        switch (requestId) {
            case 998:
                image = new Gson().fromJson(result, ImageUploadBean.class);
                if ("1".equals(image.getStatus())) {
                    ivCertificateImage.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dp2px(this, 190)));
                    ivCertificateImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    Glide.with(this).load(newFile).into(ivCertificateImage);
                }
                break;
            case 882:
                CommonBean bean = new Gson().fromJson(result, CommonBean.class);
                if (bean.getMessage().getCode() == 200) {
                    EventBus.getDefault().post(new MinePageRefreshEvent(EventKey.UPDATE_USER_CERTIFICATE));
                    this.finish();
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onException(int requestId, String code) {
        LogUtil.e("失败requestId :" + requestId + "错误码code:" + code);

        switch (requestId) {
            case 999:
                LogUtil.e("上传失败,错误码" + code);
                break;
            case 882:
                break;
            default:
                break;
        }
    }


}
